/**
 * 生命周期函数--监听页面加载
 */// pages/index/index.js
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    city: "",
    weather: { 'wea_img': 'qing' },//实况天气
    devID_list: [{ devNo: "868221047652659", nick: "设备一" }, { devNo: "868221047652659", nick: '设备二' }, { devNo: "868221047652659", nick: '设备三' }, { devNo: "868221047652659", nick: '设备四' }, { devNo: "868221047652659", nick: '设备五' }],
    dev_list: []   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取当前天气
    let that = this;
    //this.getapi();
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    wx.request({
      url: 'https://119.3.46.145/server/FindGroup?userid=' + app.globalData.userid,
      method: 'POST',
      header: header,
      success: res => {
        let groups = JSON.parse(res.data.data);
        wx.request({
          url: 'https://119.3.46.145/server/FindDevice?userid=' + app.globalData.userid,
          method: 'POST',
          header: header,
          success: res => {
            let devices = JSON.parse(res.data.devices);           
            let devCache = [];

            let points = [];
            for (let i in devices) {
              let dev = devices[i];
              let groupname = "";
              for (let j = 0; j < groups.length; j++) {
                if (groups[j].groupId == dev.groupId) {
                  groupname = groups[j].groupName;
                  break;
                }
              }

              devCache[dev.devNo] = {
                name: dev.description,
                groupId: dev.groupId
              };

              let hasclass = false;
              for (let p in points) {
                let item = points[p];
                if (item.id === dev.groupId) {
                  let childpoints = item.points;
                  childpoints.push({
                    devNo: dev.devNo,
                    devName: dev.description,
                  });
                  hasclass = true;
                }
              }

              if (!hasclass) {
                points.push({
                  name: groupname,
                  id: dev.groupId,
                  hidden:true,
                  images:'/images/group.png',
                  down:'/images/icon_down2x.png',
                  points: [
                    {
                      devNo: dev.devNo,
                      devName: dev.description
                    }
                  ]
                })
              }
            }

            that.setData({
              dev_list: points
            });          
          },
          fail: function (error) {
            console.log(error, "FindDevice error");
          }
        })


      },
      fail: function (error) {
        console.log(error, "FindDevice error");
      }
    });
    
  },

  isOpen: function (e) {
    var that = this;
    var idx = e.currentTarget.dataset.index;

    var dev_list = that.data.dev_list;
    // var curId = 0;
    dev_list.forEach(function(item, index, self){   
      if (idx == item.id) {
        if (item.hidden == true && item.down == "/images/icon_down2x.png") {
          item.down = "/images/icon_up2x.png";
        } else {
          item.down = "/images/icon_down2x.png";
        }
        item.hidden = !item.hidden;
        // curId = i;
      } else {
        item.hidden = true;
        item.down = "/images/icon_down2x.png";
      }
    });
    // }
    that.setData({
      dev_list:dev_list
    });

  
  },

  modify_dev:function(e){
    let deviceid = e.currentTarget.dataset.deviceid;
    let devClassId = e.currentTarget.dataset.devclassid;
    let devicename = e.currentTarget.dataset.devicename;

    wx.navigateTo({
      url: '../edit_dev/edit_dev?deviceid='+deviceid+'&devClassId='+devClassId+'&devicename='+devicename,
    });

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };
  },

  del_dev:function(e){
    let that = this;  
    let deviceid = e.currentTarget.dataset.deviceid;
    let devclassid = e.currentTarget.dataset.devclassid;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    wx.showModal({
      title: '提示',
      content: '是否删除设备？',
      success: function (res) {
        if (res.cancel) {
       
        } else if (res.confirm) {

          wx.request({
            url: 'https://119.3.46.145/server/DeleteDevice?userid=' + app.globalData.userid + '&deviceid=' + deviceid,
            header: header,
            success: function (res) {
              if (res.data.error == 0) {
                let tmp_list = that.data.dev_list;

                //跟新一下 全局变量  app.globalData.dev_list 获取最新的设备列表 在请求getLastInfo的时候用
                //方式一  直接请求最新的
                wx.request({
                  url: "https://119.3.46.145/server/FindDevice?userid=" + app.globalData.userid,
                  type: "post",
                  header: header,
                  success: res => {
                    app.globalData.edit_del_add_dev_flag = true; //删除了设备，标记改为 true 需要重新设置地图的 center 以及scale
                    //如果没有设备 则return
                    if (res.data == '') {
                      app.globalData.dev_list = [];
                      return;
                    }

                    let devices_data = JSON.parse(res.data.devices);
                    app.globalData.dev_list = devices_data;                   
                  },
                  fail: function (error) {

                  }
                });

                //方式二 直接修改数组
                tmp_list.forEach(function(item, index, self){
                  
                  if (item.id == devclassid){
                    let tmp_points = item.points;
                    tmp_points.forEach(function(_item, _index, _self){
                        if(_item.devNo == deviceid){
                          _self.splice(index, 1);
                          return false;
                        }
                      });
                      return false;
                    }
                });

                that.setData({
                  dev_list: tmp_list
                });              

                wx.showModal({
                  title: '信息提示',
                  content: '删除设备成功',
                  showCancel: false,
                  confirmColor: '#f37938'
                });
              }
              if (res.data.error == -1){
                wx.showModal({
                  title: '提示',
                  content: '删除设备不成功'
                })
              }
              
            },
            fail: function (resq) {
              wx.showModal({
                title: '信息提示',
                content: '删除设备失败',
                showCancel: false,
                confirmColor: '#f37938'
              });
            },
            complete: function () {
            }
          })
        }
      }      
    })
  },

  //更新name
  changeData: function (id, devNo, devName) {
    let that = this;
    let tmp_list = that.data.dev_list;

    tmp_list.forEach(function(item, index, self){
      if(item.id == id){
        item.points.forEach(function (_item, _index, _self) {
          if (_item.devNo == devNo) {
            _item.devName = devName;            
            return false;
          }
        });
        return false;
      }     
    });

    that.setData({
      dev_list:tmp_list
    });   

    //console.log(that.data.dev_list, "change dev_list");
  },

  //添加一项
  add_change: function (id, devNo, devName){
    let that = this;
    let tmp_list = that.data.dev_list;

    tmp_list.forEach(function (item, index, self) {
      if (item.id == id) {
        let tmp_points = item.points;
          tmp_points.push({
            devNo:devNo,
            devName:devName
          });
        return false;
      }
    }); 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let that = this;
    //调用定位方法
    //that.getUserLocation();
    var that = this;
  },

  //定位方法
  getUserLocation: function () {
    var _this = this;
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //未授权
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      _this.geo();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          _this.geo();
        }
        else {
          console.log('授权成功')
          //调用wx.getLocation的API
          _this.geo();
        }
      }
    })

  },

  // 获取定位城市
  geo: function () {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        // wx.request({
        //   url: 'http://api.map.baidu.com/geocoder/v2/?ak=xxxxxxxxxxxx&location=' + res.latitude + ',' + res.longitude + '&output=json',
        //   data: {},
        //   header: { 'Content-Type': 'application/json' },
        //   success: function (ops) {
        //     console.log('定位城市：', ops.data.result.addressComponent.city)
        //   },
        //   fail: function (resq) {
        //     wx.showModal({
        //       title: '信息提示',
        //       content: '请求失败',
        //       showCancel: false,
        //       confirmColor: '#f37938'
        //     });
        //   },
        //   complete: function () {
        //   }
        // })

        var qqmapsdk = new QQMapWX({
          key: 'BYXBZ-763KX-YTT4S-7SEOC-N5I23-I5BAE'
        });

        wx.getLocation({  //获取当前地址
          type: 'wgs84',
          success: function (res) {
            var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180
            //根据经纬度获取所在城市
            qqmapsdk.reverseGeocoder({
              location: { latitude: latitude, longitude: longitude },
              success: function (res) {
                //address 城市
                that.setData({ city: res.result.address_component.city })
                wx.showToast({
                  title: `当前位置： ` + that.data.city,
                  icon: 'none'
                });
              }
            });
          }
        });
      }
    })
  },

  //天气api
  getapi: function () {
    // let that = this;
    // // 获取IP地址
    // wx.request({
    //   url: 'https://tianqiapi.com/ip/',
    //   data: {
    //   },
    //   method: 'POST',
    //   header: {
    //     'content-type': 'application/x-www-form-urlencoded'
    //   },
    //   success: function (res) {
    //     console.log(res, "success res");
    //     // 根据IP获取天气数据
    //     that.weathertoday(res.data.ip);
    //   },
    //   fail: function (res) {
    //     console.log(res, "fail res")
    //   }

    // });
  },

  // 天气api实况天气
  weathertoday: function (ip) {
    let that = this;
    wx.request({
      url: 'https://tianqiapi.com/api/?version=v6',
      data: {
        'ip': ip
      },
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          weather: res.data
        });
        //console.log(that.data.weather, "weather success");
      },
      fail: function (res) {
        console.log(res, "weather fail");
      }
    });
  },

  goto_detail: function () {
    wx.navigateTo({
      url: '../detail/detail',
    })
  },

  add_dev: function () {
    wx.navigateTo({
      url: '../add_dev/add_dev',
    });
  },

  manage_group:function(){
    wx.navigateTo({
      url: '../manage_group/manage_group',
    });


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})